package com.jackeysun.util

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

/**
 *   Created by sunxunchao on 2021/11/17.
 */

/**
 * 强制显示 {@link #InputMethodManager.SHOW_FORCED}
 */
fun View.bindSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    isFocusable = true
    isFocusableInTouchMode = true
    requestFocus()
    imm.showSoftInput(this, 0)
}

fun View.unbindSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

fun Activity.forceHideSoftInput(){
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}

/**
 * 切换软键盘，如果显示则隐藏，如果隐藏则显示
 */
fun View.toggleSoftInput(): Boolean {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    return if (imm.isActive) {
        imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0)//隐藏
        false
    } else {
        isFocusable = true
        isFocusableInTouchMode = true
        requestFocus()
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)//显示
        true
    }
}

fun Context.isKeyboardShow(): Boolean {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    return imm.isActive
}
